// cloudfunctions/exportData/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

/**
 * 数据导出云函数
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    const {
      startDate,
      endDate,
      format = 'excel',
      includeCategories = true,
      includeBudgets = true
    } = event

    // 参数验证
    if (!startDate || !endDate) {
      return {
        success: false,
        code: 1001,
        message: '请指定导出的日期范围'
      }
    }

    if (!['excel', 'csv', 'json'].includes(format)) {
      return {
        success: false,
        code: 1001,
        message: '不支持的导出格式'
      }
    }

    // 构建查询条件
    const whereCondition = {
      _openid: openid,
      isDeleted: false,
      date: db.command.gte(startDate).and(db.command.lte(endDate))
    }

    // 查询账单数据
    const billsResult = await db.collection('bills')
      .where(whereCondition)
      .orderBy('date', 'desc')
      .orderBy('createTime', 'desc')
      .get()

    const bills = billsResult.data

    if (bills.length === 0) {
      return {
        success: false,
        code: 2001,
        message: '指定日期范围内没有账单数据'
      }
    }

    // 获取用户信息
    const userResult = await db.collection('users').where({
      _openid: openid
    }).get()

    const userInfo = userResult.data[0] || {}

    // 准备导出数据
    const exportData = {
      userInfo: {
        nickName: userInfo.nickName || '用户',
        exportTime: new Date().toISOString(),
        dateRange: { startDate, endDate },
        totalRecords: bills.length
      },
      bills: bills.map(bill => ({
        日期: bill.date,
        时间: bill.time,
        类型: bill.type === 'income' ? '收入' : '支出',
        分类: bill.category,
        金额: bill.amount,
        备注: bill.note || '',
        创建时间: bill.createTime
      }))
    }

    // 如果需要包含分类信息
    if (includeCategories) {
      const categoriesResult = await db.collection('categories').get()
      exportData.categories = categoriesResult.data.map(cat => ({
        名称: cat.name,
        类型: cat.type === 'income' ? '收入' : '支出',
        图标: cat.icon,
        颜色: cat.color,
        是否默认: cat.isDefault ? '是' : '否'
      }))
    }

    // 如果需要包含预算信息
    if (includeBudgets) {
      const budgetsResult = await db.collection('budgets').where({
        _openid: openid
      }).get()
      
      exportData.budgets = budgetsResult.data.map(budget => ({
        月份: budget.month,
        预算金额: budget.amount,
        已花费: budget.spent,
        剩余: budget.remaining,
        使用率: `${budget.usageRate.toFixed(1)}%`
      }))
    }

    // 生成统计信息
    let totalIncome = 0
    let totalExpense = 0
    const categoryStats = {}

    bills.forEach(bill => {
      if (bill.type === 'income') {
        totalIncome += bill.amount
      } else {
        totalExpense += bill.amount
      }

      if (!categoryStats[bill.category]) {
        categoryStats[bill.category] = {
          count: 0,
          amount: 0,
          type: bill.type
        }
      }
      categoryStats[bill.category].count++
      categoryStats[bill.category].amount += bill.amount
    })

    exportData.summary = {
      总收入: totalIncome,
      总支出: totalExpense,
      结余: totalIncome - totalExpense,
      账单数量: bills.length,
      分类统计: Object.entries(categoryStats).map(([category, stats]) => ({
        分类: category,
        类型: stats.type === 'income' ? '收入' : '支出',
        笔数: stats.count,
        金额: stats.amount
      }))
    }

    // 根据格式生成文件内容
    let fileContent
    let fileName
    let contentType

    switch (format) {
      case 'json':
        fileContent = JSON.stringify(exportData, null, 2)
        fileName = `账单数据_${startDate}_${endDate}.json`
        contentType = 'application/json'
        break
        
      case 'csv':
        // 生成CSV格式
        const csvHeaders = ['日期', '时间', '类型', '分类', '金额', '备注']
        const csvRows = [csvHeaders.join(',')]
        
        exportData.bills.forEach(bill => {
          const row = [
            bill.日期,
            bill.时间,
            bill.类型,
            bill.分类,
            bill.金额,
            `"${bill.备注.replace(/"/g, '""')}"`
          ]
          csvRows.push(row.join(','))
        })
        
        fileContent = csvRows.join('\n')
        fileName = `账单数据_${startDate}_${endDate}.csv`
        contentType = 'text/csv'
        break
        
      default: // excel
        // 这里应该生成Excel文件，简化处理返回JSON
        fileContent = JSON.stringify(exportData, null, 2)
        fileName = `账单数据_${startDate}_${endDate}.xlsx`
        contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        break
    }

    // 上传到云存储
    const uploadResult = await cloud.uploadFile({
      cloudPath: `exports/${openid}/${fileName}`,
      fileContent: Buffer.from(fileContent, 'utf8')
    })

    // 生成临时下载链接
    const downloadResult = await cloud.getTempFileURL({
      fileList: [uploadResult.fileID]
    })

    const downloadUrl = downloadResult.fileList[0].tempFileURL

    // 记录导出历史
    await db.collection('exports').add({
      data: {
        _openid: openid,
        fileName: fileName,
        fileId: uploadResult.fileID,
        format: format,
        dateRange: { startDate, endDate },
        recordCount: bills.length,
        fileSize: Buffer.byteLength(fileContent, 'utf8'),
        createTime: new Date(),
        downloadCount: 0
      }
    })

    return {
      success: true,
      code: 0,
      message: '数据导出成功',
      data: {
        downloadUrl: downloadUrl,
        fileName: fileName,
        fileSize: Buffer.byteLength(fileContent, 'utf8'),
        recordCount: bills.length,
        summary: exportData.summary
      }
    }

  } catch (error) {
    console.error('数据导出失败:', error)
    return {
      success: false,
      code: 5001,
      message: '数据导出失败，请重试',
      error: error.message
    }
  }
}